package com.data.util;

import com.alibaba.fastjson.JSON;
import com.csvreader.CsvReader;
import com.data.pojo.StockCode;
import com.data.pojo.StockData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Str
 * @Date 2022/2/16 18:13
 * @Description :
 */
@Component
public class StockUtil {
    //  全部数据
    //  日期,股票代码,名称,收盘价,最高价,最低价,开盘价,前收盘,涨跌额,涨跌幅,换手率,成交量,成交金额,总市值,流通市值
    //  fields字段表示要抓取的数据类型。
    //  http://quotes.money.163.com/service/chddata.html?code=" + code + "&start=" + startTime + "&end=" + endTime + "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP;

    @Autowired
    RedisTemplate redisTemplate;//操作k-v对象的

    // 每当获取一个新的股票数据时，就往里面添加新的数据，然后存放到redis中
    private static Map<String, String> stockCodeMap = new HashMap<>();

    public List<StockData> getStockDate(String code, String startTime, String endTime) {
        List<StockData> stockDatas = new ArrayList<>();
        List<String[]> csvList = new ArrayList<>();

        //  日期,股票代码,名称,收盘价,涨跌幅
        String urlPath = "http://quotes.money.163.com/service/chddata.html?code=" + code + "&start=" + startTime + "&end=" + endTime + "&fields=TCLOSE;PCHG;";

        System.out.println("urlPath：" + urlPath);
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式，默认是GET
//            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();

            // 建立链接从请求中获取数据
//            URLConnection con = url.openConnection();
            InputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            // 读取
            CsvReader reader = new CsvReader(bin, ',', Charset.forName("GBK"));
            reader.readHeaders(); //跳过表头,不跳可以注释掉
            while (reader.readRecord()) {
                csvList.add(reader.getValues()); //按行读取，并把每一行的数据添加到list集合
            }
            System.out.println("======================StockUtil.getStockDate.csvList=========================");
            System.out.println(csvList);
            System.out.println("======================StockUtil.getStockDate.csvList=========================");
            for (String[] aCsvList : csvList) {
                StockData stockData = new StockData();
                stockData.setDate(aCsvList[0]);
                // 由于获取到的股票代码数据为 '600000 形式，所以需要截取去除前面的 ' 符号
                stockData.setStockCode(aCsvList[1].substring(1));
                stockData.setStockName(aCsvList[2]);
                stockData.setClosingPrice(Float.valueOf(aCsvList[3]));
//                stockData.setQuoteChange(Double.valueOf(aCsvList[4]));
                stockDatas.add(stockData);
            }
            // 存放StockCode信息
            StockCode stockCode = new StockCode();
            // 由于获取到的股票代码数据为 '600000 形式，所以需要截取去除前面的 ' 符号
            stockCode.setCode(csvList.get(0)[1].substring(1));
            stockCode.setName(csvList.get(0)[2]);
            stockCodeMap.put(code, JSON.toJSONString(stockCode));
            for (String s : stockCodeMap.keySet()) {
                System.out.println("==============StockUtil.getStockDate.stockCodeMap====================");
                System.out.println("key：" + s);
                System.out.println("value：" + stockCodeMap.get(s));
                System.out.println("==============StockUtil.getStockDate.stockCodeMap====================");
            }
            // 提交数据到redis
            putStockCode(stockCodeMap);
            System.out.println("stockCode：" + JSON.toJSONString(stockCode));
            // 关闭资源
            bin.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件上传失败！");
        }
        return stockDatas;
    }

    /**
     * 提交StockCode数据
     *
     * @param map
     * @return java.lang.Long
     */
    public Long putStockCode(Map<String, String> map) {
        // 先清除原来的数据
        redisTemplate.delete("all_stock_code");
        return redisTemplate.opsForSet().add("all_stock_code", map);
    }

    public Map<String, String> getStockCode() {
        return stockCodeMap;
    }
}
